package android.rockchip.update.receivers;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.rockchip.update.OtaUpdates;
import android.rockchip.update.RomUpdate;
import android.rockchip.update.service.RKUpdateService;
import android.rockchip.update.utils.Constants;
import android.rockchip.update.utils.Preferences;
import android.text.TextUtils;
import android.util.Log;

import java.util.Iterator;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class AppReceiver extends BroadcastReceiver implements Constants {

    public final String TAG = this.getClass().getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Bundle extras = intent.getExtras();
        long mRomDownloadID = Preferences.getDownloadID(context);
        Log.d(TAG, "action = " + action);
        if (TextUtils.equals(action, DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            if (extras == null) return;
            long id = extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
            boolean isAddonDownload = false;

            Set<Integer> set = OtaUpdates.getAddonDownloadKeySet();
            Iterator<Integer> iterator = set.iterator();

            while (iterator.hasNext() && !isAddonDownload) {
                int nextValue = iterator.next();
                if (id == OtaUpdates.getAddonDownload(nextValue)) {
                    isAddonDownload = true;
                    Log.d(TAG, "Checking ID " + nextValue);
                }
            }

            Log.e(TAG, "Receiving " + mRomDownloadID);
            if (id != mRomDownloadID) {
                Log.e(TAG, "Ignoring unrelated non-ROM download " + id);
                return;
            }

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(id);
            Cursor cursor = dm.query(query);

            // it shouldn't be empty, but just in case
            if (!cursor.moveToFirst()) {
                Log.e(TAG, "Rom download Empty row");
                return;
            }

            int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (DownloadManager.STATUS_SUCCESSFUL != cursor.getInt(statusIndex)) {
                Log.w(TAG, "Download Failed");
                Preferences.setDownloadFinished(context, false);
            } else {
                Log.e(TAG, "Download Succeeded");
                Preferences.setDownloadFinished(context, true);
                Log.e(TAG, "ota package下载完成," + Preferences.getUpdateDescription(context));
                Intent finishIntent = new Intent("android.rockchip.update.service.DOWNLOADFINISH");
                finishIntent.putExtra("otaDescrition", Preferences.getUpdateDescription(context));
                context.sendBroadcast(finishIntent);
            }
        } else if (TextUtils.equals(action, DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            if (extras == null) return;
            long[] ids = extras.getLongArray(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            for (long id : ids) {
                if (id != mRomDownloadID) {
                    Log.e(TAG, "mDownloadID is " + mRomDownloadID + " and ID is " + id);
                    return;
                }
            }
        } else if (TextUtils.equals(action, START_UPDATE_CHECK)) {
            Intent serviceIntent = new Intent("android.rockchip.update.service");
            serviceIntent.setPackage("android.rockchip.update.service");
            serviceIntent.putExtra("command", RKUpdateService.COMMAND_CHECK_REMOTE_UPDATING);
            serviceIntent.putExtra("delay", 15000);
            context.startService(serviceIntent);
        } else if (TextUtils.equals(action, Intent.ACTION_BOOT_COMPLETED)) {
            scheduleCheckUpdate(context);
        } else if (TextUtils.equals(action, IGNORE_RELEASE)) {
            Preferences.setIgnoredRelease(context,
                    Integer.toString(RomUpdate.getVersionNumber(context)));
        }
    }

    public void scheduleCheckUpdate(final Context context) {
        long INTERVAL = Preferences.getBackgroundFrequency(context) * 1000;
        ScheduledExecutorService executorService;
        executorService = Executors.newSingleThreadScheduledExecutor();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "scheduleCheckUpdate begin");
                Intent intent = new Intent(context, AppReceiver.class);
                intent.setAction(START_UPDATE_CHECK);
                context.sendBroadcast(intent);
            }
        };
        executorService.scheduleWithFixedDelay(task, INTERVAL, INTERVAL, TimeUnit.MILLISECONDS);
    }

}


